<template>
  <div>
    <div class="cropper-content">
      <div class="cropper">
        <vueCropper
          ref="cropper"
          :img="imgoption.img"
          :outputSize="imgoption.size"
          :outputType="imgoption.outputType"
          :info="true"
          :infoTrue="imgoption.infoTrue"
          :full="imgoption.full"
          :canMove="imgoption.canMove"
          :canMoveBox="imgoption.canMoveBox"
          :original="imgoption.original"
          :autoCrop="imgoption.autoCrop"
          :autoCropWidth="imgoption.autoCropWidth"
          :autoCropHeight="imgoption.autoCropHeight"
          :fixedBox="imgoption.fixedBox"
          @realTime="realTime"
          :centerBox="imgoption.centerBox"
          :high="imgoption.high"
          :maxImgSize="imgoption.maxImgSize"
          :enlarge="imgoption.enlarge"
          :limitMinSize="imgoption.limitMinSize"
        ></vueCropper>
      </div>
      <div
        class="show-preview"
        :style="{
          width: previews.w + 'px',
          height: previews.h + 'px',
          overflow: 'hidden',
        }"
      >
        <div :style="previews.div" class="preview">
          <img :src="previews.url" :style="previews.img" />
        </div>
      </div>
    </div>
    <div class="footer-btn">
      <div class="el-btn">
        <div class="scope-btn" style="margin: 12px">
          <label class="btn" for="uploads">更换图片</label>
          <input
            type="file"
            id="uploads"
            style="position: absolute; clip: rect(0 0 0 0)"
            accept="image/png, image/jpeg, image/gif, image/jpg"
            @change="uploadImg($event)"
          />
        </div>
        <el-button
          type="success"
          icon="el-icon-circle-plus-outline"
          circle
          @click="changeScale(1)"
        ></el-button>
        <el-button
          type="success"
          icon="el-icon-remove-outline"
          circle
          @click="changeScale(-1)"
        ></el-button>
        <el-button
          type="success"
          icon="el-icon-refresh-left"
          circle
          @click="rotateLeft()"
        ></el-button>
        <el-button
          type="success"
          icon="el-icon-refresh-right"
          circle
          @click="rotateRight()"
        ></el-button>
        <div style="margin-left: 30px">
          <el-button type="success" @click="down('blob')"
            ><i class="el-icon-upload el-icon--right"></i>上传</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      previews: {},
      imgoption: {
        img: "",
        size: 1,
        outputType: "png",
        info: true,
        full: false,
        canMove: false,
        canMoveBox: true,
        fixedBox: true,
        original: true,
        autoCrop: true,
        autoCropWidth: 120,
        autoCropHeight: 120,
        centerBox: true,
        high: false,
        infoTrue: true,
        enlarge: 1,
        maxImgSize: 200,
        limitMinSize: [100, 120],
        fileName: "",
      },
      userInfo: {
        _id: this.$store.getters.UserInfoID,
      },
      downImg: "#",
    };
  },
  methods: {
    handleExceed() {
      this.$message.warning("头像上传失败！，请重新选择");
    },
    changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
    finish(type) {
      // 输出
      if (type === "blob") {
        this.$refs.cropper.getCropBlob((data) => {
          var img = window.URL.createObjectURL(data);
          this.model = true;
          this.modelSrc = img;
        });
      } else {
        this.$refs.cropper.getCropData((data) => {
          this.model = true;
          this.modelSrc = data;
        });
      }
    },
    //实时预览函数
    realTime(data) {
      this.previews = data;
    },
    down() {
      // event.preventDefault()
      // 输出
      this.$refs.cropper.getCropBlob((data) => {
        this.downImg = window.URL.createObjectURL(data);
        let formData = new FormData();
        // 向 formData 对象中添加文件
        formData.append("file", data, this.imgoption.fileName);
        formData.append("userInfoID", this.userInfo._id);
        formData.append("userInfoLogoUrl", this.$store.getters.UserInfoLogoUrl);
        //封装axios方法
        this.axios.post("/user/upload", formData).then((response) => {
          if (response.data.data.code == 200) {
            this.$message({
              message: "上传成功",
              type: "success",
            });
            this.$store.commit("updataUserInfo", {
              logoUrl: response.data.data.url,
            });
            this.$emit("changeImg");
          } else {
            this.$message.error("上传失败，请重新选择");
          }
        });
      });
    },
    uploadImg(e) {
      //上传图片 //
      this.imgoption.fileName = e.target.files[0].name;
      var file = e.target.files[0];
      if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
        alert("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种");
        return false;
      }
      var reader = new FileReader();
      reader.onload = (e) => {
        let data;
        if (typeof e.target.result === "object") {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        this.imgoption.img = data;
      };
      // 转化为base64
      // reader.readAsDataURL(file)
      // 转化为blob
      reader.readAsArrayBuffer(file);
    },
  },
};
</script>

<style scoped>
.cropper-content {
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  -webkit-justify-content: flex-end;
  margin-top: 10px;
}
.cropper {
  width: 200px;
  height: 200px;
  margin-left: 10px;
}
.show-preview {
  flex: 1;
  -webkit-flex: 1;
  display: flex;
  display: -webkit-flex;
  justify-content: center;
  -webkit-justify-content: center;
  margin: auto;
}
.preview {
  overflow: hidden;
  border-radius: 50%;
  border: 1px solid white;
  background: white;
  margin-left: 40px;
}

.footer-btn {
  margin-top: 10px;
  margin-bottom: 5px;
}
.btn {
  outline: none;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  -webkit-appearance: none;
  text-align: center;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  outline: 0;
  margin: 0;
  -webkit-transition: 0.1s;
  transition: 0.1s;
  font-weight: 500;
  padding: 8px 15px;
  font-size: 12px;
  border-radius: 3px;
  color: #fff;
  background-color: #67c23a;
  border-color: #67c23a;
}
.el-btn {
  display: flex;
  display: -webkit-flex;
  justify-content: flex-start;
  -webkit-justify-content: flex-start;
  margin-left: 5px;
}
.el-btn :nth-child(6) {
  margin-right: 0;
}
.el-btn >>> .el-button {
  font-size: 12px;
}
</style>